<template>
  <div class="approval">
    <el-card class="box-card" style="margin-top: 110px;">
      <div class="title">{{$t('achievements.title1')}}</div>
      <div class="menu-search">
        <div class="menu-title">
          <!-- APP渠道 -->
          <div class='searchItem'>
            <span>{{$t('ElectricChannel.AppChannel')}}</span>
            <el-select v-model='listQuery.channel' @change="handleChannelChanged"  size='small'>
                <el-option
                v-for='item in appChannel'
                :key='item.channel'
                :label='item.org_name'
                :value='item.channel'>
                </el-option>
            </el-select>
          </div>
          <!-- 包名 -->
          <div class="searchItem">
            <span>{{$t('ElectricChannel.packageName')}}</span>
            <el-select v-model="listQuery.packageName" filterable size="small">
              <el-option 
                v-for="item in packageList"
                :key="item.dictCode"
                :label="item.dictCode"
                :value=item.dictCode></el-option>
            </el-select>
          </div>
          <!-- 名称 -->
          <div class="searchItem">
            <span>{{$t('group.name')}}</span>
            <el-input
              v-model="listQuery.title"
              size="small"
              :placeholder="$t('NoticeManager.inpSearchName')"
            ></el-input>
          </div>
          <div class="menu-title-btn" style="margin-left: 20px;">
            <button type="button" @click="search">{{$t('btn.query')}}</button>
          </div>
        </div>
      </div>
    </el-card>
    <el-card class="box-card" style="margin-top: 10px;margin-bottom: 20px;">
      <div style="display: flex; justify-content: space-between;">
        <div class="title">{{$t('DailyStatistics.ListDetails')}}</div>
        <div class='menu-list'>
            <button type='button' @click="handleCreate">{{$t('btn.add')}}</button>
        </div>
      </div>
      <el-table
        v-loading="listLoading"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%; margin-top: 5px;"
        border
        size="mini"
      >
        <el-table-column
          :label="$t('user.num')"
          header-align="center"
          align="center"
          width="60"
        >
          <template slot-scope="scope">
            <span>{{scope.row.index}}</span>
          </template>
        </el-table-column>
        <!-- 名称 -->
        <el-table-column
          header-align="center"
          align="center"
          prop="title"
          :label="$t('group.name')"
        ></el-table-column>
        <!-- 状态 -->
        <el-table-column
          header-align="center"
          align="center"
          width="160"
          :label="$t('grouping.status')"
        >
          <template slot-scope="scope">
            <el-radio-group v-model="scope.row.status" size="small" @change.native="changeStatus(scope.row)">
                <el-radio label="1" size="mini">{{$t("AppVersion.enable")}}</el-radio>
                <el-radio label="2" size="mini">{{$t("AppVersion.blockup")}}</el-radio>
            </el-radio-group>
          </template>
        </el-table-column>
        <el-table-column align="center" header-align="center" :label="$t('user.operation')" width="100" fixed="right">
          <template slot-scope="scope">
                <!-- 编辑 -->
                <el-button size="small" type="text" @click="handleUpdate(scope.row)">{{$t('btn.edit')}}
                </el-button>
                <!-- 删除 -->
                <el-button size="small" type="text" @click="handleDelete(scope.row)" style="color: #f56c6c;">{{$t('btn.delete')}}
                </el-button>
            </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.page"
          :page-sizes="[10, 30, 50]"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :before-close="closeDialog"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" style="width: 80%;margin-left: 10%;">
        <!-- 包名 -->
        <el-form-item :label="$t('ElectricChannel.packageName')" prop="packageName">
          <el-select v-model="form.packageName" filterable size="small">
              <el-option 
                v-for="item in packageList"
                :key="item.dictCode"
                :label="item.dictCode"
                :value=item.dictCode></el-option>
            </el-select>
        </el-form-item>
        <!-- 广告名称 -->
        <el-form-item :label="$t('NoticeManager.adName')" prop="title">
          <el-input size="small" v-model="form.title" :maxlength="50" :placeholder="$t('NoticeManager.adNameLimit')"></el-input>
        </el-form-item>
        <!-- 活动图片 -->
        <el-form-item :label="$t('NoticeManager.ActivePictures')" prop="file">
          <el-checkbox-group v-model="form.file">
          </el-checkbox-group>
          <div class="item_bock head_p">
              <div class="head_img">
                  <img :src="form.newsrc" alt="">
              </div>
              <button type="button" class="click-img" @click.stop="uploadHeadImg">{{$t('AppUpgrade.subUpload')}}</button>
              <div style="font-size: 12px;color: #666;line-height: 20px;">*{{$t('NoticeManager.imgRule')}}</div>
              <form action="" id="videoForm">
                <input type="file" accept="image/jpg,image/png,image/jpeg" @change="handleFile" class="hiddenInput"/>
              </form>
          </div>
          </el-form-item>
          <!-- 状态 -->
          <el-form-item :label="$t('grouping.status')" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio label="1" size="small">{{$t('grouping.enable')}}</el-radio>
              <el-radio label="2" size="small">{{$t('AppVersion.blockup')}}</el-radio>
            </el-radio-group>
          </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
            <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')">{{$t('btn.conserve')}}</el-button>
            <el-button v-else type="primary" @click="update('form')">{{$t('btn.conserve')}}</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getChannels, getDictByChannelAndPackageName } from "api/customQuery/index";
import {
  page,
  addObj,
  updateObj,
  deleteById,
  updateNoticeStatus
} from 'api/synManager/NoticeManager/index';
import { uploadFile } from 'api/synManager/creditSupermarket/cashLoan/index'
export default {
  data() {
    return {
      textMap: {
        update: this.$t('btn.edit'),
        create: this.$t('btn.create')
      },
      dialogStatus: '',
      form: {
        title: undefined,
        packageName: '',
        status: '1',
        file: '',
        newsrc: ''
      },
      rules: {
        packageName: [
          {
            required: true,
            message: this.$t('rule.choose')
          }
        ],
        title: [
          {
            required: true,
            message: this.$t("NoticeManager.inpAdName")
          }
        ],
        file: [
          {
            required: true,
            message: this.$t("NoticeManager.uploadImg")
          }
        ],
        status: [
          {
            required: true,
            message: this.$t("NoticeManager.ruleStatus")
          }
        ]
      },
      dialogFormVisible: false,
      listLoading: false,
      total: null,
      expDis: true,
      listQuery: {
        limit: 10,
        page: 1,
        title: '',
        channel: '',
        packageName: ''
      },
      tableData: [],
      userGroupArr: [
        {
          value: '',
          label: this.$t('rule.all')
        }
      ],
      appChannel: [],
      packageList: [],
      currentId: ''
    };
  },
  computed: {
    ...mapGetters(["elements", "NoticeManagerPage"])
  },
  created() {
    if (this.NoticeManagerPage.has(this.$route.path)) {
      this.listQuery = this.NoticeManagerPage.get(this.$route.path);
    }
    // 渠道下拉
    getChannels().then(res => {
      this.appChannel = res.data;
      // 级联查询包名
      getDictByChannelAndPackageName({
        channel: this.appChannel[0].channel,
        packageName: ''
      }).then(res => {
        if (res.data && res.data.length) {
          this.packageList = res.data
          this.listQuery.channel = this.appChannel[0].channel;
          this.getList();
        } else {
          this.packageList = []
          // this.$message({
          //   showClose: true,
          //   type: 'warning',
          //   message: res.message
          // });
        }
      })
    });
  },
  methods: {
    handleChannelChanged(value) {
      getDictByChannelAndPackageName({
        channel: value,
        packageName: ''
      }).then(res => {
        if (res.data && res.data.length) {
          this.packageList = res.data
          this.listQuery.packageName = ''
        } else {
          this.packageList = []
          // this.$message({
          //   showClose: true,
          //   type: 'warning',
          //   message: res.message
          // });
        }
      })
    },
    resetForm() {
      this.form = {
        packageName: '',
        title: undefined,
        status: '1',
        file: ''
      }
    },
    // 打开图片上传
    uploadHeadImg () {
      this.$el.querySelector('.hiddenInput').click()
    },
    // 将头像显示
    handleFile (e) {
      let $target = e.target || e.srcElement
      let files = $target.files[0]
      var imgSize = files.size;
      if (imgSize > 2 * 1024 * 1024){
        this.$message({
          showClose: true,
          type: "warning",
          message: this.$t('NoticeManager.imgLimit')
        });
        document.getElementById('videoForm')&&document.getElementById('videoForm').reset();
      } else {
        var reader = new FileReader()
        reader.readAsDataURL(files)
        reader.onload = (data) => {
          let res = data.target || data.srcElement
          this.form.newsrc = res.result
          $(".head_img img").attr("src", res.result);
        }
        this.form.file = files;
      }
    },
    closeDialog(done) {
      done();
      this.$refs["form"].resetFields();
      this.getList();
    },
    // 点击添加按钮
    handleCreate() {
      this.resetForm();
      this.dialogStatus = 'create';
      this.dialogFormVisible = true;
    },
    dataURLtoFile(dataurl, filename) {
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, { type: mime });
    },
    // 图片的绝对路径地址,转换成base64编码
    getBase64Image(img) {
      var canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, img.width, img.height);
      var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
      var dataURL = canvas.toDataURL("image/"+ext);
      return {
        dataURL: dataURL,
        type: "image/"+ext
      };
    },
    // 点击编辑按钮
    handleUpdate(row) {
      this.dialogStatus = "update";
      this.currentId = row.id;
      this.form = Object.assign({}, row);
      this.form.newsrc = row.imgUrl;
      // this.form.file = row.imgUrl;
      var path = this.form.newsrc.substring(this.form.newsrc.lastIndexOf("/")+1, this.form.newsrc.length)
      var image = new Image();
      image.crossOrigin = '';
      image.src = this.form.newsrc;
      image.onload = () => {
        var base64 = this.getBase64Image(image);
        /*
        打印信息如下：
        {
          dataURL: ""
          type: "image/jpg"
        }
        */
        var imgFile = this.dataURLtoFile(base64.dataURL, path)
        this.form.file = imgFile;
      } 
      this.dialogFormVisible = true;
    },
    // 添加保存按钮
    create(formName) {
      const set = this.$refs;
      set[formName].validate(valid => {
        if (valid) {
          this.$confirm(this.$t('loanDetail.cue1'), {
              confirmButtonText: this.$t('btn.confirm'),
              cancelButtonText: this.$t('btn.cancel'),
              type: "warning",
              center: true
            })
            .then(() => {
              let obj = new FormData();
              obj.append('file', this.form.file);
              obj.append('title', this.form.title);
              obj.append('status', this.form.status);
              obj.append('channel', this.listQuery.channel);
              obj.append('packageName', this.form.packageName);
              addObj(obj).then(response => {
                if (response.status === 200) {
                  this.dialogFormVisible = false;
                  this.getList();
                  this.$notify({
                    title: this.$t("user.success"),
                    message: this.$t("user.crtsuccess"),
                    type: "success",
                    duration: 2000
                  });
                } else {
                  this.$message({
                    showClose: true,
                    type: "warning",
                    message: response.message
                  });
                }
              });
            })
            .catch(() => {
              this.$message({
                showClose: true,
                type: "info",
                message: this.$t('loanDetail.cue3')
              });
            });
        } else {
          return false;
        }
      });
    },
    // 编辑保存按钮
    update(formName) {
      const set = this.$refs;
      set[formName].validate(valid => {
        if (valid) {
          this.$confirm(this.$t("loanDetail.cue1"), {
              confirmButtonText: this.$t("btn.confirm"),
              cancelButtonText: this.$t("btn.cancel"),
              type: "warning",
              center: true
          })
            .then(() => {
              let obj = new FormData();
              obj.append('id', this.currentId);
              obj.append('file', this.form.file);
              obj.append('title', this.form.title);
              obj.append('status', this.form.status);
              obj.append('channel', this.form.channel);
              obj.append('packageName', this.form.packageName);
              updateObj(obj).then(response => {
                if (response.status === 200) {
                  this.dialogFormVisible = false;
                  this.getList();
                  this.$notify({
                    title: this.$t("user.success"),
                    message: this.$t("wordbook.wbeditsuc"),
                    type: "success",
                    duration: 2000
                  });
                } else {
                  this.$message({
                    showClose: true,
                    type: "warning",
                    message: response.message
                  });
                }
              });
            })
            .catch(() => {
                this.$message({
                    showClose: true,
                    type: "info",
                    message: this.$t("loanDetail.cue3")
                });
            });
        } else {
          return false;
        }
      });
    },
    // 点击删除按钮
    handleDelete(row) {
      this.$confirm(this.$t('user.cue1'), this.$t('user.cue2'), {
        confirmButtonText: this.$t('btn.confirm'),
        cancelButtonText: this.$t('btn.cancel'),
        type: 'warning'
      })
        .then(() => {
          let obj = {};
          obj.id = row.id;
          deleteById(obj).then(() => {
            this.$notify({
              title: this.$t("user.success"),
              message: this.$t("user.delsuccess"),
              type: "success",
              duration: 2000
            });
            const index = this.tableData.indexOf(row);
            this.tableData.splice(index, 1);
            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            showClose: true,
            type: "info",
            message: this.$t('orderQuery.cue2')
          });
        });
    },
    // 修改状态
    changeStatus(row) {
      let obj = {};
      obj.id = row.id;
      obj.status = row.status;
      updateNoticeStatus(obj).then(res => {
        if (res.status === 200) {
          this.$message({
            showClose: true,
            type: "success",
            message: this.$t("approvalDispatch.opersuccess")
          });
          this.getList();
        } else {
          this.$message({
            showClose: true,
            type: "warning",
            message: res.message
          });
          this.getList();
        }
      });
    },
    getList() {
      this.listLoading = true;
      this.$store.dispatch("saveNoticeManagerPage", {
        path: this.$route.path,
        listQuery: this.listQuery
      });
      page(this.listQuery).then(res => {
        if (res.status === 200) {
          res.data.records.forEach((item, index) => {
            item.index =
              index + (this.listQuery.page - 1) * this.listQuery.limit + 1;
          });
          this.expDis = false;
          this.listLoading = false;
          this.tableData = res.data.records;
          this.total = Number(res.data.total);
        } else {
          this.$message({
            showClose: true,
            type: "warning",
            message: res.message
          });
        }
      });
    },
    //查询
    search() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    }
  }
};
</script>

<style scoped lang='scss'>
.box-card {
  width: 95%;
  margin-left: 2.5%;
  margin-right: 2.5%;
}
.title {
  line-height: 30px;
  font-size: 16px;
  display: flex;
  align-items: center;
  font-weight: bold;
}
.title:before {
  display: block;
  content: "";
  width: 3px;
  height: 16px;
  background-color: #309afe;
}
.title:before {
  margin-right: 8px;
}
::before {
  box-sizing: inherit;
  -webkit-tap-highlight-color: transparent;
}
.menu-title {
  width: 100%;
  box-sizing: border-box;
  background: #ffffff;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .searchItem {
    display: flex;
    align-items: center;
    padding: 10px 0;
    span {
      display: inline-block;
      width: 100px;
      text-align: right;
      font-size: 12px;
      color: #5f5f61;
      padding-right: 5px;
    }
    div:nth-child(2) {
      width: 200px;
    }
  }
  .searchItem-date {
    display: flex;
    align-items: center;
    padding: 10px 0;
    b {
      margin: 0 10px;
      font-weight: normal;
      font-size: 12px;
      color: #5f5f61;
    }
    div {
      width: 150px;
    }
  }
}
.menu-title-btn {
  padding: 10px 0;
  box-sizing: border-box;
  button {
    padding: 0 20px;
    height: 28px;
    background: #20a0ff;
    color: #fff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
    margin-left: 10px;
    &:nth-child(1) {
      margin-left: 0;
    }
    &:nth-child(2) {
      background: #ebf5ff;
      color: #20a0ff;
      border: 1px solid #abd5ff;
    }
  }
  button[disabled] {
    padding: 0 20px;
    height: 28px;
    background: #c1e0ff;
    color: #fafbff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
  }
}
.menu-list {
  button {
    padding: 0 20px;
    height: 28px;
    background: #20a0ff;
    color: #fff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
    margin-left: 10px;
    &:nth-child(1) {
      margin-left: 0;
    }
  }
  button[disabled] {
    padding: 0 20px;
    height: 28px;
    background: #c1e0ff;
    color: #fafbff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
  }
}
.item_bock {
  width: 100%;
  background: #fff;
  display: flex;
  flex-direction: column;
}
.head_img {
  width: 100%;
  height: 200px;
  border: 1px solid #ccc;
  margin-bottom: 10px;
  border-radius: 4px;
}
.head_img img{
  width: 100%;
  height: 200px;
  border-radius: 4px;
}
.hiddenInput{
  display: none;
}
.click-img {
  width: 100%;
  height: 28px;
  line-height: 28px;
  background: #20a0ff;
  color: #fff;
  outline: none;
  border-width: 0;
  font-size: 12px;
  border-radius: 4px;
}
</style>